<?php

use Yjius\fileshandler\FilesHandlerBuilder;

require __DIR__ . "/../../vendor/autoload.php";

$ossParams = require dirname(__DIR__) . "/config/files-handler/oss.php";

$localParams = require dirname(__DIR__) . "/config/files-handler/local.php";

try {
    //LOCAL 大文件上传-方法三连
    //跨域修改
    ini_set('display_errors', 'On');
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
    header('Access-Control-Allow-Credentials: true');
    header("Access-Control-Allow-Headers: x-token,access-token,stime,sign,Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since");
    header("Access-Control-Allow-Credentials:true"); // 设置cookie必须设置
    $action = isset($_GET['action']) ? $_GET['action'] : '';
    $res = [];
    $up = new FilesHandlerBuilder($localParams);
    if ($action == 'merge') { //合并
        $post = file_get_contents('php://input');
        $data = json_decode($post, true);
        $res = $up->merge([
            'filename' => htmlentities($data['filename']), //文件名称
            'identifier' => htmlentities($data['identifier']), //文件唯一标识
            'totalSize' => intval($data['totalSize']), //文件总大小
            'totalChunks' => intval($data['totalChunks']) //总分片数
        ]);
    } else {
        $method = $_SERVER['REQUEST_METHOD'];
        if ($method === 'POST') { //上传
            $res = $up->upload([
                'identifier' => htmlentities($_POST['identifier']), //每个文件的唯一标识
                'filename' => htmlentities($_POST['filename']), //文件名称
                'totalSize' => intval($_POST['totalSize']), //文件总大小
                'chunkNumber' => intval($_POST['chunkNumber']), //当前是第几个分片
                'totalChunks' => intval($_POST['totalChunks']) //总分片数
            ]);
        } elseif ($method == 'GET') { //上传前检测文件md5和分片
            $res = $up->checkFile([
                'identifier' => htmlentities($_GET['identifier']), //每个文件的唯一标识
                'filename' => htmlentities($_GET['filename']), //文件名称
                'totalSize' => intval($_GET['totalSize']), //文件总大小
                'totalChunks' => intval($_GET['totalChunks']) //总分片数
            ]);
        }
    }
    echo json_encode($res);
    exit;
} catch (Exception $exception) {
    echo $exception->getMessage();
    exit;
}
